<?php

namespace Acme\CommonBundle\Controller;

use Symfony\Component\BrowserKit\Request;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Acme\CommonBundle\Entity\ConstUniversity;

/**
 * @Route("/university")
 */
class UniversityController extends Controller
{
	/**
	 * @Route("/js_university_generator", name="AcmeCommonBundle_JsUniversityGenerator")
	 * @Template()
	 */
	public function jsUniversityGeneratorAction() {
		$em = $this->getDoctrine()->getEntityManager();
		$temp_data = $em->getRepository('AcmeCommonBundle:ConstUniversity')->findAll();
		foreach ($temp_data as $v) {
			if ($v instanceof ConstUniversity) {
				$data[] = array('id' => $v->getId(), 'name' => $v->getName());
			}
		}
		
		return array('data' => json_encode($data));
	}

	/**
	 * @Route("/ajax_get_university", name="AcmeCommonBundle_AjaxGetUniversity")
	 */
	public function ajaxGetUniversityAction() {
		$request = $this->get('request');
		 
		if ($request->isXmlHttpRequest()) {
			$term = urldecode($request->get('term'));

			$em = $this->getDoctrine()->getEntityManager();
			$temp_data = $em->getRepository('AcmeCommonBundle:ConstUniversity')->findUniversityByTerm($term);
			if (!empty($temp_data)) {
				foreach ($temp_data as $k => $v) {
					$data[] = array('id' => $v->getId(), 'label' => $v->getName());
				}
				return new Response(json_encode($data));
			} else {
				return new Response(null);
			}
		}
	}
}
